﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using AmiCheckin.Code.Util;
using AmiCheckin.Lib;
using AmiCheckin.Lib.Model;
using PropertyChanged;

namespace AmiCheckin.UI.ViewModels
{
    [AddINotifyPropertyChangedInterface]
    public class CheckinSetsViewModel
    {
        public ObservableCollection<ObservableCheckinSet> CheckinSetObjects { get; set; } = new();

        public void Load()
        {
            var config = ConfigUtil.GetConfig();
            CheckinSetObjects.Clear();
            config.CheckinSets.ToList().ForEach(x =>
            {

                CheckinSetObjects.Add(new()
                {
                    Name = x.Key,
                    Keywords = new(x.Value.Keywords),
                    Replies = new(x.Value.Replies),
                    SpecialGroups = new(x.Value.SpecialGroups),
                    Rewards = new(x.Value.Rewards.Select(r => new ObservableRewardRangeSet()
                    {
                        RewardKey = r.Key,
                        Min = r.Value.Min,
                        Max = r.Value.Max
                    }))
                });
            });


        }

        public void Save()
        {
            var config = ConfigUtil.GetConfig();

            var dic = config.CheckinSets;
            dic.Clear();
            foreach (var item in CheckinSetObjects)
            {
                dic.Add(item.Name, new CheckinSet()
                {
                    Keywords = new(item.Keywords),
                    Replies = new(item.Replies),
                    SpecialGroups = new(item.SpecialGroups),
                    Rewards = item.Rewards.ToDictionary(x => x.RewardKey, x => new RangeSet() { Min = x.Min, Max = x.Max })
                });
            }
            config.CheckinSets = dic;
            ConfigUtil.SetConfig(config);
        }
    }

    [AddINotifyPropertyChangedInterface]
    public class ObservableCheckinSet
    {
        public string Name { get; set; }
        public ObservableCollection<string> Keywords { get; set; } = new();
        public ObservableCollection<string> Replies { get; set; }= new();
        public ObservableCollection<long> SpecialGroups { get; set; }= new();
        public ObservableCollection<ObservableRewardRangeSet> Rewards { get; set; }= new();
    }


    [AddINotifyPropertyChangedInterface]
    public class ObservableRewardRangeSet
    {

        public string RewardKey { get; set; }
        public double Min { get; set; }
        public double Max { get; set; }

        public KeyValuePair<string, RangeSet> Turn()
        {
            return new KeyValuePair<string, RangeSet>(RewardKey, new(Min, Max));
        }
    }

}